<?php 
//访问链接
//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc4c916331ca3a95a&redirect_uri=http://www.ynong888.com/project/wechat/login/login.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect


$config = [
                        'appid'=>'wx2d1290a0a9bf3435', 
                        'secret'=>'973b24adb0debc6355d6cdfb8a1e133c'
                        ];


if(isset($_GET["code"]))
{
	$code = $_GET['code'];
	$channel = $_GET['state'];


	$api_url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$config['appid']}&secret={$config['secret']}&code=".$code."&grant_type=authorization_code";
	$api_result = file_get_contents($api_url);
	
	$api = json_decode($api_result);
	if(isset($api->{'errcode'}))
	{
		echo $code;
		echo "  api error ";
		echo $api_result;
	}else
	{

		$access_token = $api->{'access_token'};
		$openid = $api->{'openid'};

		$user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
		$user_info_result = file_get_contents($user_info_url);

		$user_info = json_decode($user_info_result);
		if(isset($user_info->{'errcode'}))
		{
			echo "user_info error ";
			echo $user_info_result;
		
		}else
		{
			$openid = $user_info->{'openid'};
			$nickname = $user_info->{'nickname'};
			$sex = $user_info->{'sex'};
			$country = $user_info->{'country'};
			$province = $user_info->{'province'};
			$city = $user_info->{'city'};	
			$headimgurl = $user_info->{'headimgurl'};

			$result = array('openid' => $openid, 
						'nickname'=>$nickname,
						'sex'=>$sex,
						'country'=>$country,
						'province'=>$province,
						'city'=>$city,
						'headimgurl'=>$headimgurl
				);
			$app_param_encode = $_GET['apparam'];
			$app_param = base64_decode($app_param_encode);
			system("echo \"".$app_param."\n\" >> /tmp/app_param.log");
			$url = "http://www.qmcsl.cn/bin/index.html?channel=".$channel."&openid=".$openid."&nickname=".$nickname."&sex=".$sex."&country=".$country."&province=".$province."&city=".$city."&headimgurl=".$headimgurl."&".$app_param;
			header("Location:".$url);
		}
	}
}
else {
	$app_param = '';//implode("&", $_GET);
	foreach ($_GET as $key => $value) {
		$app_param .= "&".$key."=".$value;
	}
	$app_param = substr($app_param, 1, strlen($app_param));
	$app_param_encode = base64_encode($app_param);
	$redirect_uri = "http://www.qmcsl.cn/wechat/login/login.php?apparam=".$app_param_encode;
	$start_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$config['appid']}&redirect_uri=".urlencode($redirect_uri)."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
	header("Location:".$start_url);
}

?>
